package com.df.excel_export.web.configs;

import com.df.excel_export.common.ExportTask;
import com.df.excel_export.utils.ExcelTools;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.core.*;
import org.apache.logging.log4j.core.appender.AbstractAppender;
import org.apache.logging.log4j.core.config.plugins.Plugin;
import org.apache.logging.log4j.core.config.plugins.PluginAttribute;
import org.apache.logging.log4j.core.config.plugins.PluginFactory;
import org.apache.logging.log4j.core.filter.AbstractFilter;
import org.apache.logging.log4j.core.layout.PatternLayout;

import java.io.Serializable;

@Plugin(name = "WebSocketAppender", category = Core.CATEGORY_NAME, elementType = Appender.ELEMENT_TYPE)
public class MyLog4jFilter extends AbstractAppender {

    protected MyLog4jFilter(String name, Filter filter, Layout<? extends Serializable> layout) {
       super(name,filter,layout);
    }

    @Override
    public void append(LogEvent event) {
        String loggerName = event.getLoggerName();
        if(!loggerName.equals(ExportTask.class.getName())){
            return;
        }
        String formattedMessage = new String(getLayout().toByteArray(event));
//        sessions.values().forEach(session -> {
//            if (session.isOpen()) {
//                session.getAsyncRemote().sendText(formattedMessage);
//            }
//        });
        Level level = event.getLevel();
        if(level.equals(Level.INFO)){
            ExcelTools.addHandleMsg(formattedMessage);
            return;
        }
        if(level.equals(Level.WARN)){
            ExcelTools.addWarningMsg(formattedMessage);
            return;
        }
        if(level.equals(Level.ERROR)){
            ExcelTools.addErrorMsg(formattedMessage);
            return;
        }
    }



    @PluginFactory
    public static MyLog4jFilter createAppender(
            @PluginAttribute("name") String name,
            @PluginAttribute("ignoreExceptions") boolean ignoreExceptions) {
        Layout<? extends Serializable> layout = PatternLayout.createDefaultLayout();
        return new MyLog4jFilter(name, null, layout);
    }
}